package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.ChanPinLeiBie;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.bean.Plan;
import com.cz.nongyetongv5.bean.TextInfo;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.bean.YangPin;
import com.cz.nongyetongv5.bean.YangPinBianHao;
import com.cz.nongyetongv5.custom.wheelview.Utils;
import com.cz.nongyetongv5.utils.AsyncClienter;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.Conf;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5_1.adapter.ListAdapter;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


public class YangPinAddActivity extends Activity implements OnClickListener {

    EditText inputBh;


    private final static int SCANNIN_GREQUEST_CODE = 23;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 23) {

            Bundle bundle = data.getExtras();
            final String str = bundle.getString("result");

            Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    inputBh.setText(str);
                    if (!str.equals("")) {
                        inputBh.setSelection(str.length());
                        if (yangPin.getBianHao() == null)
                            yangPin.setBianHao(new YangPinBianHao());
                        yangPin.getBianHao().setEwmString(str);
                    }
                }
            });


        } else if (resultCode == TO_CHOUYANGPAIZHAO) {

            if (data != null) {
                ArrayList<Photo> photos = (ArrayList<Photo>) data.getExtras()
                        .getSerializable("photos");

                if (photos != null) {
                    this.yangPin.setPhotos(photos);

                }
            }

            surePaiZhao();

        } else {
            Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override
                public void run() {

                }
            });

        }

    }

    private ViewGroup btnBack = null;

    private ViewGroup btnSure = null;
    private DatabaseHelper db = null;
    private String planId = "";
    private ChanPinLeiBie chanPinLeiBie = null;


    /**
     * 样品编号
     */
    private ViewGroup yangpinxinxi_bianhao = null;

    /**
     * 样品名称
     */
    private ViewGroup yangpinxinxi_mingcheng = null;
    /**
     * asdasd
     */
    protected ViewGroup rl_chanpinjiance_item_chanpinleibie = null;
    /**
     * 样品地点
     */
    private ViewGroup yangpinxinxi_yangpindidian = null;

    /**
     * 样品基数
     */
    private ViewGroup yangpinxinxi_yangpinjishu = null;

    /**
     * 规格型号
     */
    private ViewGroup yangpinxinxi_guigexinghao = null;

    /**
     * 样品信息对象
     */
    private YangPin yangPin = null;

    private User user = null;

    /*
     * 产品类别
     */
    private ChanPinLeiBie chanpinleibie;

    private ConfigUtil configUtil = null;

    // 样品信息
    private List<YangPin> datas = null;

    private boolean edit = false;

    private void initView() {
        rl_chanpinjiance_item_chanpinleibie = (ViewGroup) this
                .findViewById(R.id.rl_chanpinjiance_item_chanpinleibie);
        rl_chanpinjiance_item_chanpinleibie.setOnClickListener(this);
        btnBack = (ViewGroup) findViewById(R.id.btnBack);

        btnBack.setOnClickListener(this);

        btnSure = (ViewGroup) findViewById(R.id.btnSure);
        btnSure.setOnClickListener(this);

        yangpinxinxi_bianhao = (ViewGroup) findViewById(R.id.yangpinxinxi_bianhao);
        yangpinxinxi_bianhao.setOnClickListener(this);

        yangpinxinxi_mingcheng = (ViewGroup) findViewById(R.id.yangpinxinxi_mingcheng);
        yangpinxinxi_mingcheng.setOnClickListener(this);

        yangpinxinxi_yangpindidian = (ViewGroup) findViewById(R.id.yangpinxinxi_yangpindidian);

        if (configUtil.getConfig() == 2) {

            yangpinxinxi_yangpindidian.setOnClickListener(this);
        } else {
            yangpinxinxi_yangpindidian.setVisibility(View.GONE);
        }

        yangpinxinxi_yangpinjishu = (ViewGroup) findViewById(R.id.yangpinxinxi_yangpinjishu);
        yangpinxinxi_yangpinjishu.setOnClickListener(this);

        yangpinxinxi_guigexinghao = (ViewGroup) findViewById(R.id.yangpinxinxi_guigexinghao);
        yangpinxinxi_guigexinghao.setOnClickListener(this);


    }

    private void initConfig() {
        db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
                CommonConstants.DATABASE_VERSION);

        if (yangPin == null) {
            yangPin = new YangPin();

            String id = UUID.randomUUID().toString().replaceAll("-", "");
            yangPin.setId(id);
        }

        /**
         * 拿到用户对象
         */
        user = (User) getIntent().getSerializableExtra("user");
        planId = getIntent().getStringExtra("planId");
        chanpinleibie = (ChanPinLeiBie) getIntent().getSerializableExtra(
                "chanpinleibie");

        /**
         * 数据集合
         */
        datas = (List<YangPin>) getIntent().getSerializableExtra("data");

        // 获得样品
        yangPin = (YangPin) getIntent().getSerializableExtra("yangpin");

        if (yangPin == null) {

            yangPin = new YangPin();

        }
        chanPinLeiBie = db.queryChanPinLeiBie(yangPin.getKind() + "");
        if (chanPinLeiBie != null)
            Log.d("rafekind", chanPinLeiBie.getName() + "");
        // 是否为编辑模式也
        edit = getIntent().getExtras().getBoolean("edit", false);

        if (edit) {


            yangpinxinxi_bianhao.setClickable(false);
        }
    }

    @Override
    protected void onDestroy() {

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().remove(this);

        // TODO Auto-generated method stub
        if (db != null)
            db.close();

        super.onDestroy();
    }

    /**
     * 抽样拍照
     */
    private ViewGroup rl_chanpinjiance_item_chouyangpaizhao = null;
    /**
     * 抽样拍照
     */
    private ViewGroup rl_chanpinjiance_item_laiyuan = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        configUtil = new ConfigUtil(getResources());

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().add(this);

        setContentView(R.layout.yangpinxinxiadd);

        initView();

        rl_chanpinjiance_item_chouyangpaizhao = (ViewGroup) findViewById(R.id.rl_chanpinjiance_item_chouyangpaizhao);
        rl_chanpinjiance_item_chouyangpaizhao.setOnClickListener(this);
        rl_chanpinjiance_item_laiyuan = (ViewGroup) findViewById(R.id.yangpinxinxi_laiyuan);
        rl_chanpinjiance_item_laiyuan.setOnClickListener(this);

        initConfig();
        sureChanPinLeiBie();
        sureBianHao();

        sureName();
        if (ChanPinJianCeActivity.bjdw != null) {

            yangPin.setLocale(ChanPinJianCeActivity.bjdw.getAddress());
        }
        sureChouYangDiDian();

        sureYangPinJiShu();
        sureSource();
        sureGuiGeXingHao();
        surePaiZhao();
        this.sureChanPinLeiBie();
    }

    /**
     * 检测拍照
     */
    public boolean checkPaiZhao() {

        if (this.yangPin.getUploadPhoto() != null) {
            return true;
        } else {
            return false;
        }

    }


    private void surePaiZhao() {

        ViewGroup photoLayout = (ViewGroup) rl_chanpinjiance_item_chouyangpaizhao
                .findViewById(R.id.llContentDescript);

        photoLayout.setVisibility(View.INVISIBLE);

        if (checkPaiZhao()) {

            toggleIconChange(rl_chanpinjiance_item_chouyangpaizhao, true);

            photoLayout.removeAllViews();

            photoLayout.setVisibility(View.VISIBLE);

            Photo photo = yangPin.getUploadPhoto();


            ImageView imageView = new ImageView(this);

            imageView.setClickable(false);


            int widthOrHeight = Utils.dip2px(this, 50);

            int marginLeft = Utils.dip2px(this, 8);

            MarginLayoutParams rootLayoutPrams = new MarginLayoutParams(
                    widthOrHeight, widthOrHeight);

            rootLayoutPrams.setMargins(marginLeft, 0, 0, 0);

            // 兼容低版本设置margin方法
            LayoutParams layoutPrarams = new LayoutParams(
                    rootLayoutPrams);
            layoutPrarams.gravity = Gravity.TOP | Gravity.LEFT;

            imageView.setLayoutParams(layoutPrarams);
            imageView.setScaleType(ScaleType.CENTER_CROP);


            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 2;

            Bitmap image = BitmapFactory.decodeFile(
                    (String) photo.getSmallPhotoPath(), opts);

            if (photo.getSmallPhotoPath() instanceof String) {
                imageView.setImageBitmap(image);

            }

            photoLayout.addView(imageView);


        } else {
            toggleIconChange(rl_chanpinjiance_item_chouyangpaizhao, false);
        }

    }

    private Plan checkPlan(String id) {

        if (id == null || id.equals(""))
            return null;
        Plan plan = db
                .queryPlanByID(id);
        if (plan != null) {

            return plan;
        }
        return null;
    }

    /**
     * 去抽样拍照
     */
    public static final int TO_CHOUYANGPAIZHAO = 3;

    @Override
    public void onClick(View v) {


        /**
         * 抽样拍照
         */
        if (v == rl_chanpinjiance_item_chouyangpaizhao) {

            Intent to_paizhao_intent = new Intent(this,
                    PaiZhaoActivity.class);
            to_paizhao_intent.putExtra("photos",
                    (Serializable) this.yangPin.getPhotos());

            to_paizhao_intent.putExtra("title", "抽样拍照");
            to_paizhao_intent.putExtra("type", "single");
            startActivityForResult(to_paizhao_intent, TO_CHOUYANGPAIZHAO);

        }

        if (v == rl_chanpinjiance_item_chanpinleibie) {

            final AlertDialog bottomWindow = new AlertDialog.Builder(
                    new ContextThemeWrapper(this,
                            R.style.NongYeTongFullscreenTheme)).create();

            // 输入法的设置
            bottomWindow.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            // 设置窗口的动画
            bottomWindow.getWindow().setWindowAnimations(R.style.bottomAnimStyle);


            bottomWindow.show();

            /**
             * 检查行业底部的布局
             */
            ViewGroup bottomLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_jianchaneirong, null);

            // 让底部的宽度和屏幕的宽度一致
            bottomLayout.setMinimumWidth(this.getWindowManager()
                    .getDefaultDisplay().getWidth());

            // 设置底部布局
            bottomWindow.setContentView(bottomLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

            // 设置标题

            TextView tvTitle = (TextView) bottomLayout
                    .findViewById(R.id.bottomTitle);

            tvTitle.setText(getString(R.string.chanpinjiance_chanpinleibie_title));

            /**
             * 进行视图的动态生成
             */
            ViewGroup layout = (ViewGroup) bottomLayout
                    .findViewById(R.id.jianchaneironglayout);
            // 清理视图
            layout.removeAllViews();

            // 查询出所有检查行业
            String[] ps = null;
            Plan plan = checkPlan(planId);
            if (plan != null)
                ps = plan.arrayEntProduces();

            List<ChanPinLeiBie> chanPinLeiBies = new ArrayList<ChanPinLeiBie>();

            List<ChanPinLeiBie> jianYanLeiBies1 = db.queryAllChanPinLeiBie();
            if (ps != null) {
                for (int i = 0; i < jianYanLeiBies1.size(); i++) {
                    if (Arrays.binarySearch(ps, jianYanLeiBies1.get(i).getId().toString()) >= 0) {
                        chanPinLeiBies.add(jianYanLeiBies1.get(i));
                    }
                }

            } else {
                chanPinLeiBies = jianYanLeiBies1;

            }


            final List<CheckBox> cbsCheckBoxs = new ArrayList<CheckBox>();

            // 遍历检查行业进行视图的生成
            for (final ChanPinLeiBie temp : chanPinLeiBies) {

                final RelativeLayout rootLayout = new RelativeLayout(
                        this);

                MarginLayoutParams rootLayoutPrams = new MarginLayoutParams(
                        MarginLayoutParams.MATCH_PARENT,
                        MarginLayoutParams.WRAP_CONTENT);

                rootLayoutPrams.setMargins(0, Utils.dip2px(this, 3),
                        0, Utils.dip2px(this, 3));

                // 兼容低版本设置margin方法
                LayoutParams layoutPrarams = new LayoutParams(rootLayoutPrams);
                layoutPrarams.gravity = Gravity.TOP | Gravity.LEFT;

                rootLayout.setLayoutParams(layoutPrarams);
                rootLayout.setClickable(true);
                rootLayout.setGravity(Gravity.CENTER_VERTICAL);
                rootLayout.setPadding(Utils.dip2px(this, 8),
                        Utils.dip2px(this, 5),
                        Utils.dip2px(this, 8),
                        Utils.dip2px(this, 5));
                rootLayout
                        .setBackgroundResource(R.drawable.jiandujiancha_item_style);

                /*********************************************/
                TextView tvItemTitle = new TextView(this);

                RelativeLayout.LayoutParams rlItemLayout = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                rlItemLayout.addRule(RelativeLayout.CENTER_VERTICAL);
                tvItemTitle.setLayoutParams(rlItemLayout);

                tvItemTitle.setPadding(Utils.dip2px(this, 8),
                        Utils.dip2px(this, 8),
                        Utils.dip2px(this, 8),
                        Utils.dip2px(this, 8));
                tvItemTitle.setTextColor(Color.parseColor("#656769"));
                tvItemTitle.setTextSize(20);
                tvItemTitle.setText(temp.getName());

                rootLayout.addView(tvItemTitle);

                /*********************************************/

                CheckBox cbCheckBox = new CheckBox(this);

                /**
                 * 清理多选
                 */
                cbCheckBox
                        .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                            @Override
                            public void onCheckedChanged(
                                    CompoundButton buttonView, boolean isChecked) {

                                /**
                                 * 单选,清理checkbox
                                 */
                                for (CheckBox checkBox : cbsCheckBoxs) {
                                    checkBox.setChecked(false);
                                }

                                buttonView.setChecked(isChecked);

                            }
                        });

                cbCheckBox.setTag(temp);

                RelativeLayout.LayoutParams cbBeiJianChaHangYeLayout = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                cbBeiJianChaHangYeLayout
                        .addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                cbBeiJianChaHangYeLayout
                        .addRule(RelativeLayout.CENTER_VERTICAL);
                cbCheckBox.setLayoutParams(cbBeiJianChaHangYeLayout);

                if (temp.equals(getChanPinLeiBie())) {
                    cbCheckBox.setChecked(true);
                } else {
                    cbCheckBox.setChecked(false);
                }

                cbCheckBox.setButtonDrawable(R.drawable.checkbox_select_style);

                rootLayout.addView(cbCheckBox);

                rootLayout.setTag(cbCheckBox);

                // 增加到缓存集合中
                cbsCheckBoxs.add(cbCheckBox);

                layout.addView(rootLayout);

                // 绑定事件,当布局被点击的时候选中checkbox
                rootLayout.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        if (rootLayout.getTag() instanceof CheckBox) {

                            CheckBox cbsJianChaNeiRong = (CheckBox) rootLayout
                                    .getTag();

                            // 将指定项选中
                            if (cbsJianChaNeiRong.isChecked()) {
                                cbsJianChaNeiRong.setChecked(false);
                            } else {
                                cbsJianChaNeiRong.setChecked(true);
                            }

                        }

                    }
                });

            }

            // 底部Window 的返回按钮
            ViewGroup btnBottomBack = (ViewGroup) bottomLayout
                    .findViewById(R.id.btnBack);

            btnBottomBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    bottomWindow.dismiss();
                }
            });

            // 选择区域底部的确定按钮
            ViewGroup btnSure = (ViewGroup) bottomLayout
                    .findViewById(R.id.btnSureJianChaNeiRong);

            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    // 如果已经选择了样品信息则提示
                    setChanPinLeiBie(null);

                    for (CheckBox checkBox : cbsCheckBoxs) {

                        if (checkBox.getTag() instanceof ChanPinLeiBie
                                && checkBox.isChecked()) {

                            ChanPinLeiBie data = (ChanPinLeiBie) checkBox
                                    .getTag();
                            setChanPinLeiBie(data);
                            chanpinleibie = data;
                            yangPin.setKind(chanpinleibie.getId());

                            break;
                        }

                    }
                    sureChanPinLeiBie();
                    bottomWindow.dismiss();

                }
            });


        }
        /**
         * 退出
         */
        if (v == btnBack) {

            finish();
        }
        /**
         * 退出
         */
        if (v == btnBack) {

            finish();
        }

        /**
         * 确定添加样品
         */
        if (v == btnSure) {

            /**
             * 进行判断样品编号
             */
            if (!yangPin.checkBianHao()) {
                DialogUtil.showMessageDialog("请填写样品编号..", null, this);

                return;
            }

            /**
             * 进行判断样品名称
             */
            if (!yangPin.checkYangPinName()) {

                DialogUtil.showMessageDialog("请填写样品名称...", null, this);

                return;
            }

            if (configUtil.getConfig() == 2) {

                /**
                 * 进行判断抽样地点
                 */
                if (!yangPin.checkLocale()) {

                    DialogUtil.showMessageDialog("请填写抽样地点...", null, this);
                    return;
                }
            }

            /**
             * 进行判断样品基数
             */
            if (!yangPin.checkJiShu()) {

                DialogUtil.showMessageDialog("请填写样品基数...", null, this);

                return;
            }

            /**
             * 进行判断规格型号,如果是水产品的话
             */

            if (chanpinleibie != null && chanpinleibie.getId() == 3) {
                if (!yangPin.checkXingHao()) {
                    DialogUtil.showMessageDialog("请填写规格型号..", null, this);
                    return;
                }
            }

            //				if (yangPin.getSource()==null||yangPin.getSource().equals("")) {
            //					DialogUtil.showMessageDialog("请填写样品来源..", null, this);
            //					return;
            //				}
            //

            /**
             * 判断样品编号是否存在
             */
            if (datas != null && datas.contains(yangPin)) {

                DialogUtil.showMessageDialog("样品编号已经存在..", null, this);

                return;
            }

            if (CommonConstants.isNetworkConnected(YangPinAddActivity.this)
                    && !edit) {

                /**联网检查*/
                checkBianhao(yangPin.getBianHaoString());
            } else {

                Intent data_intent = new Intent();

                data_intent.putExtra("yangpin", yangPin);

                data_intent.putExtra("edit", edit);

                setResult(YangPinXinXiActivity.TO_ADD_YANGPINXINXI, data_intent);

                finish();

            }

        }
        final AlertDialog bottomWindow = new AlertDialog.Builder(
                new ContextThemeWrapper(this, R.style.NongYeTongFullscreenTheme))
                .create();

        // 输入法的设置
        bottomWindow.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

        // 设置窗口的动画
        bottomWindow.getWindow().setWindowAnimations(R.style.bottomAnimStyle);

        /**
         * 点击样品编号的时候
         */
        if (v.getId() == R.id.toewm) {

            Intent intent = new Intent();
            intent.setClass(this, MipcaActivityCapture.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent, SCANNIN_GREQUEST_CODE);

        }
        if (v == yangpinxinxi_bianhao) {

            bottomWindow.show();

            // 让底部的宽度和屏幕的宽度一致
            ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_yangpinxinxi_bianhao, null);
            inputBh = (EditText) bottomBeiJianDanWeiWindowLayout.findViewById(R.id.edtBianHao);
            bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                    .getWindowManager().getDefaultDisplay().getWidth());
            bottomBeiJianDanWeiWindowLayout.findViewById(R.id.toewm).setOnClickListener(this);
            // 设置底部布局
            bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

            TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.tvTitle);

            tvTitle.setText(getString(R.string.chanpinjiance_ypbh_title));


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            /**
             * 样品编号的前缀
             */
            String pre = user.getLocalPySimple() + sdf.format(new Date()) + "-";

            inputBh.setText(pre);
            inputBh.setSelection(pre.length());

            // 数据还原
            if (yangPin.checkBianHao()) {
                inputBh.setText(yangPin.getBianHao().getEwmString());
                inputBh.setSelection(yangPin.getBianHao().getEwmString().length());
            }


            // 彈出软键盘
            //			final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            //			imm.showSoftInput(inputBh, InputMethodManager.RESULT_SHOWN);
            //			imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
            //					InputMethodManager.HIDE_IMPLICIT_ONLY);


            ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnBack);

            btnBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    // 隐藏软键盘
                    //imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    bottomWindow.dismiss();
                }
            });

            ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnSure);

            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    // 隐藏软键盘
                    //imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    //					 if(yangPin.getBianHao()!=null&&yangPin.getBianHao().getEwmString()!=null){
                    //						    sureBianHao();
                    //                             bottomWindow.dismiss();
                    //							return;
                    //
                    //					 }


                    //					if (!CharsetUtil.checkYangPinBianHaoLiangWei(bianHao1)) {
                    //
                    //						Toast.makeText(YangPinAddActivity.this,
                    //								"样品编号非法,请检查...", Toast.LENGTH_SHORT).show();
                    //
                    //						inputBh.requestFocus();
                    //
                    //						return;
                    //
                    //					}


                    YangPinBianHao bianHao = new YangPinBianHao();
                    bianHao.setEwmString(inputBh.getText().toString());
                    yangPin.setBianHao(bianHao);

                    if (datas != null && datas.contains(yangPin)) {

                        Toast.makeText(YangPinAddActivity.this, "样品编号已经存在..",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    sureBianHao();

                    bottomWindow.dismiss();
                }
            });

        }

        /**
         * 点击样品名称的时候
         */
        if (v == yangpinxinxi_mingcheng) {
            //  if( ChouyangrenwuActivity.getCheckPlan()!=null){
            selmingchen(bottomWindow);
            //            	 return;
            //             }
            //
            //			bottomWindow.show();
            //
            //			// 让底部的宽度和屏幕的宽度一致
            //			ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
            //					.getLayoutInflater().inflate(
            //							R.layout.bottom_photodetail_comment, null);
            //
            //			bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
            //					.getWindowManager().getDefaultDisplay().getWidth());
            //
            //			// 设置底部布局
            //			bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);
            //
            //			// 弹出输入法的操作
            //			bottomWindow.getWindow().clearFlags(
            //					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            //
            //			bottomWindow.getWindow().setGravity(Gravity.BOTTOM);
            //
            //			TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
            //					.findViewById(R.id.tvTitle);
            //
            //			tvTitle.setText(getString(R.string.chanpinjiance_ypmc_title));
            //
            //			final TextView edtContent = (TextView) bottomBeiJianDanWeiWindowLayout
            //					.findViewById(R.id.edtCommentPhoto);
            //
            //			edtContent.setHint("请输入样品名称");
            //
            //			// 设置最多15个字符
            //			edtContent
            //					.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            //							15) });
            //
            //			// 数据还原
            //			if (yangPin.checkYangPinName()) {
            //
            //				edtContent.setText(yangPin.getName());
            //
            //			}
            //
            //			ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
            //					.findViewById(R.id.btnBack);
            //
            //			btnBack.setOnClickListener(new OnClickListener() {
            //
            //				@Override
            //				public void onClick(View v) {
            //
            //					bottomWindow.dismiss();
            //				}
            //			});
            //
            //			ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
            //					.findViewById(R.id.btnSure);
            //
            //			btnSure.setOnClickListener(new OnClickListener() {
            //
            //				@Override
            //				public void onClick(View v) {
            //
            //					String yangPinMingCheng = edtContent.getText().toString()
            //							.trim();
            //
            //					if (!CharsetUtil.isNotNull(yangPinMingCheng)) {
            //
            //						Toast.makeText(YangPinAddActivity.this, "请输入样品名称...",
            //								Toast.LENGTH_SHORT).show();
            //
            //						return;
            //					}
            //
            //					// 设置样品名称
            //
            //					yangPin.setName(yangPinMingCheng);
            //
            //					sureName();
            //
            //					bottomWindow.dismiss();
            //				}
            //			});

        }
        if (v == rl_chanpinjiance_item_laiyuan) {


            bottomWindow.show();

            // 让底部的宽度和屏幕的宽度一致
            ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_photodetail_comment, null);

            bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                    .getWindowManager().getDefaultDisplay().getWidth());

            // 设置底部布局
            bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

            TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.tvTitle);

            tvTitle.setText("样品来源");

            final TextView edtContent = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.edtCommentPhoto);
            edtContent.setHint("请输入样品来源，例如'2号塘口,3号地块'");//rafely

            // 设置最多字符
            edtContent
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            50)});
            // 数据还原
            if (yangPin.getSource() != null && !yangPin.getSource().equals("")) {

                edtContent.setText(yangPin.getSource());

            }

            ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnBack);

            btnBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    bottomWindow.dismiss();
                }
            });

            ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnSure);

            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String chouYangDiDian = edtContent.getText().toString()
                            .trim();

                    //					if (!CharsetUtil.isNotNull(chouYangDiDian)) {
                    //
                    //						Toast.makeText(YangPinAddActivity.this, "请输入 样品来源...",
                    //								Toast.LENGTH_SHORT).show();
                    //
                    //						return;
                    //					}

                    // 设置样品名称

                    yangPin.setSource(chouYangDiDian);

                    sureSource();

                    bottomWindow.dismiss();
                }
            });


        }
        /**
         * 当点击抽样地点的时候
         */
        if (v == yangpinxinxi_yangpindidian) {

            bottomWindow.show();

            // 让底部的宽度和屏幕的宽度一致
            ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_addr, null);

            bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                    .getWindowManager().getDefaultDisplay().getWidth());

            // 设置底部布局
            bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);


            addrinput = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.edt_addr);

            addrinput.setHint("请输入抽样地点,例如'基地'");
            if (ChanPinJianCeActivity.bjdw != null)
                addrinput.setText(ChanPinJianCeActivity.bjdw.getAddress());
            // 设置最多字符
            addrinput
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            50)});
            // 数据还原
            if (yangPin.checkLocale()) {

                addrinput.setText(yangPin.getLocale());

            }

            ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnBack);

            btnBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    bottomWindow.dismiss();
                }
            });

            ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnSure);
            bottomBeiJianDanWeiWindowLayout.findViewById(R.id.todw).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dwdo();
                }
            });
            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String chouYangDiDian = addrinput.getText().toString()
                            .trim();

                    if (!CharsetUtil.isNotNull(chouYangDiDian)) {

                        Toast.makeText(YangPinAddActivity.this, "请输入 抽样地点...",
                                Toast.LENGTH_SHORT).show();

                        return;
                    }

                    // 设置样品名称

                    yangPin.setLocale(chouYangDiDian);

                    sureChouYangDiDian();

                    bottomWindow.dismiss();
                }
            });

        }

        /**
         * 当点击样样品基数的时候
         */
        if (v == yangpinxinxi_yangpinjishu) {

            bottomWindow.show();

            // 让底部的宽度和屏幕的宽度一致
            ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_photodetail_comment, null);

            bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                    .getWindowManager().getDefaultDisplay().getWidth());

            // 设置底部布局
            bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

            TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.tvTitle);

            tvTitle.setText(getString(R.string.chanpinjiance_ypjs_title));

            final TextView edtContent = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.edtCommentPhoto);

            edtContent.setHint("请输入样品基数,例如\u0020“1公斤/100公斤”,表示100公斤中采样1公斤");

            // 设置最多字符
            edtContent
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            15)});
            // 数据还原
            if (yangPin.checkJiShu()) {

                edtContent.setText(yangPin.getJiShu());

            }

            ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnBack);

            btnBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    bottomWindow.dismiss();
                }
            });

            ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnSure);

            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String content = edtContent.getText().toString().trim();

                    if (!CharsetUtil.isNotNull(content)) {

                        Toast.makeText(YangPinAddActivity.this, "请输入 样品基数...",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 设置样品名称

                    yangPin.setJiShu(content);

                    sureYangPinJiShu();

                    bottomWindow.dismiss();
                }
            });

        }

        /**
         * 当点击规格型号的时候
         */
        if (v == yangpinxinxi_guigexinghao) {

            bottomWindow.show();

            // 让底部的宽度和屏幕的宽度一致
            ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                    .getLayoutInflater().inflate(
                            R.layout.bottom_photodetail_comment, null);

            bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                    .getWindowManager().getDefaultDisplay().getWidth());

            // 设置底部布局
            bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

            // 弹出输入法的操作
            bottomWindow.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

            bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

            TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.tvTitle);

            tvTitle.setText(getString(R.string.chanpinjiance_ggxh_title));

            final TextView edtContent = (TextView) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.edtCommentPhoto);

            edtContent.setHint("请输入规格型号");

            // 设置最多字符
            edtContent
                    .setFilters(new InputFilter[]{new InputFilter.LengthFilter(
                            15)});

            // 数据还原
            if (yangPin.checkXingHao()) {
                edtContent.setText(yangPin.getXingHao());
            }

            ViewGroup btnBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnBack);

            btnBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    bottomWindow.dismiss();
                }
            });

            ViewGroup btnSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                    .findViewById(R.id.btnSure);

            btnSure.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    String content = edtContent.getText().toString().trim();

                    if (!CharsetUtil.isNotNull(content)) {

                        // 水产品则必须输入
                        if (chanpinleibie!= null && chanpinleibie.getId() == 3) {
                            Toast.makeText(YangPinAddActivity.this,
                                    "请输入 规格型号...", Toast.LENGTH_SHORT).show();
                            return;

                        }

                        content = "-";
                    }

                    // 设置样品名称

                    yangPin.setXingHao(content);

                    sureGuiGeXingHao();

                    bottomWindow.dismiss();
                }
            });

        }

    }

    public void sureBianHao() {

        TextView tvContentDescript = (TextView) yangpinxinxi_bianhao
                .findViewById(R.id.content_bianhao);

        if (yangPin.checkBianHao()) {

            toggleIconChange(yangpinxinxi_bianhao, true);

            tvContentDescript.setText(yangPin.getBianHaoString());

        } else {
            toggleIconChange(yangpinxinxi_bianhao, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 确认样品名称
     */
    public void sureName() {

        TextView tvContentDescript = (TextView) yangpinxinxi_mingcheng
                .findViewById(R.id.content_name);

        if (yangPin.checkYangPinName()) {

            toggleIconChange(yangpinxinxi_mingcheng, true);

            tvContentDescript.setText(yangPin.getName());

        } else {

            toggleIconChange(yangpinxinxi_mingcheng, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 确认抽样地点
     */
    public void sureChouYangDiDian() {

        TextView tvContentDescript = (TextView) yangpinxinxi_yangpindidian
                .findViewById(R.id.content_yangpindidian);

        if (yangPin.checkLocale()) {

            toggleIconChange(yangpinxinxi_yangpindidian, true);

            tvContentDescript.setText(yangPin.getLocale());

        } else {

            toggleIconChange(yangpinxinxi_yangpindidian, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 确认抽样地点
     */
    public void sureSource() {

        TextView tvContentDescript = (TextView) this.rl_chanpinjiance_item_laiyuan
                .findViewById(R.id.content_laiyuan);

        if (yangPin.getSource() != null && !yangPin.getSource().equals("")) {
            toggleIconChange(rl_chanpinjiance_item_laiyuan, true);
            tvContentDescript.setText(yangPin.getSource());

        } else {

            toggleIconChange(rl_chanpinjiance_item_laiyuan, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 确定样品基数
     */
    public void sureYangPinJiShu() {

        TextView tvContentDescript = (TextView) yangpinxinxi_yangpinjishu
                .findViewById(R.id.content_yangpinjishu);

        if (yangPin.checkJiShu()) {

            toggleIconChange(yangpinxinxi_yangpinjishu, true);

            tvContentDescript.setText(yangPin.getJiShu());

        } else {

            toggleIconChange(yangpinxinxi_yangpinjishu, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 确定规格型号
     */
    public void sureGuiGeXingHao() {

        TextView tvContentDescript = (TextView) yangpinxinxi_guigexinghao
                .findViewById(R.id.content_guigexinghao);

        if (yangPin.checkXingHao()) {

            toggleIconChange(yangpinxinxi_guigexinghao, true);

            tvContentDescript.setText(yangPin.getXingHao());

        } else {

            toggleIconChange(yangpinxinxi_guigexinghao, false);
            tvContentDescript.setText("");

        }

    }

    /**
     * 改变选择的图标
     */
    private void toggleIconChange(ViewGroup viewGroup, boolean selected) {

        View ivChangeIcon = viewGroup.findViewWithTag("ivChangeIcon");

        Animation imageFadeIn = AnimationUtils.loadAnimation(
                YangPinAddActivity.this, R.anim.icon_anim_move_x);

        if (ivChangeIcon != null && ivChangeIcon instanceof ImageView) {

            ImageView imageView = (ImageView) ivChangeIcon;

            /**
             * 如果是更多则切换为
             */
            if (selected) {
                imageView.setImageResource(R.drawable.item_select);
            } else {
                imageView.setImageResource(R.drawable.jiandujiancha_icon_more);
            }
            // 加载进入

            imageView.clearAnimation();

            imageView.setAnimation(imageFadeIn);

            imageFadeIn.start();
        }
    }

    public void toggleIconChange2(ViewGroup viewGroup, boolean selected) {

        View ivChangeIcon = viewGroup.findViewWithTag("ivChangeIcon");

        Animation imageFadeIn = AnimationUtils.loadAnimation(this,
                R.anim.icon_anim_move_x);

        if (ivChangeIcon != null && ivChangeIcon instanceof ImageView) {

            ImageView imageView = (ImageView) ivChangeIcon;

            /**
             * 如果是更多则切换为
             */
            if (selected) {
                imageView.setImageResource(R.drawable.item_select);
            } else {
                imageView
                        .setImageResource(R.drawable.jiandujiancha_icon_more);
            }
            // 加载进入

            imageView.clearAnimation();

            imageView.setAnimation(imageFadeIn);

            imageFadeIn.start();
        }
    }

    public ChanPinLeiBie getChanPinLeiBie() {
        return chanPinLeiBie;
    }

    public void setChanPinLeiBie(ChanPinLeiBie chanPinLeiBie) {
        this.chanPinLeiBie = chanPinLeiBie;
    }

    private void sureChanPinLeiBie() {

        TextView tvContentDescript = (TextView) rl_chanpinjiance_item_chanpinleibie
                .findViewById(R.id.content_chanpinleibie);

        if (getChanPinLeiBie() != null) {

            toggleIconChange(rl_chanpinjiance_item_chanpinleibie, true);

            tvContentDescript.setText(getChanPinLeiBieStr());
        } else {
            toggleIconChange(rl_chanpinjiance_item_chanpinleibie, false);
            tvContentDescript.setText("");

        }


    }

    public String getChanPinLeiBieStr() {

        StringBuffer txtBuffer = new StringBuffer();

        ChanPinLeiBie temp = getChanPinLeiBie();

        txtBuffer.append(temp.getName());

        txtBuffer.append(". ");

        return txtBuffer.toString().trim();

    }

    int page = 0;

    public void selmingchen(final AlertDialog bottomWindow) {


        bottomWindow.show();
        page = 0;
        // 让底部的宽度和屏幕的宽度一致
        ViewGroup bottomBeiJianDanWeiWindowLayout = (ViewGroup) this
                .getLayoutInflater().inflate(R.layout.bottom_beijiandanwei2,
                        null);

        bottomBeiJianDanWeiWindowLayout.setMinimumWidth(this
                .getWindowManager().getDefaultDisplay().getWidth());

        // 设置底部布局
        bottomWindow.setContentView(bottomBeiJianDanWeiWindowLayout);

        // 弹出输入法的操作
        bottomWindow.getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

        bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

        // 进行标题的绑定
        TextView tvTitle = (TextView) bottomBeiJianDanWeiWindowLayout
                .findViewById(R.id.tvTitle);
        tvTitle.setText("样品名称");


        /**
         * 加载被检单位
         */
        final ListView wvBeiJianDanWei = (ListView) bottomBeiJianDanWeiWindowLayout.findViewById(R.id.dataview);


        adpBeiJianDanWeiAdapter = new ListAdapter(this);
        wvBeiJianDanWei.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int arg2, long arg3) {
                wvBeiJianDanWei.setTag(arg2);
                adpBeiJianDanWeiAdapter.setSelectItem(arg2);
                adpBeiJianDanWeiAdapter.notifyDataSetInvalidated();

            }
        });
        wvBeiJianDanWei.setAdapter(adpBeiJianDanWeiAdapter);

        etBeiJianDanWeiFilter = (EditText) bottomBeiJianDanWeiWindowLayout
                .findViewById(R.id.etBeiJianDanWeiFilter);
        class onPage {
            public void onClick(int arg0) {
                String filter = String.valueOf(etBeiJianDanWeiFilter.getText());
                String url = Conf.v1609_presample + "GetTaskBreed";
                String tid = "0";
                if (ChouyangrenwuActivity.getCheckPlan() != null) {
                    tid = ChouyangrenwuActivity.getCheckPlan().optString("id");
                }
                String param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                        + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                        + "<soap:Body>"
                        + "<GetTaskBreed xmlns=\"http://tempuri.org/\">"
                        + "<nAddFrom>1</nAddFrom>"
                        + "<szAddFirm>android</szAddFirm>"
                        + "<nOffset>" + (page * 10) + "</nOffset>"
                        + "<nSize>10</nSize>"
                        + "<szJsonPara>{\"user\":\"" + user.getUsername() + "\", \"task_id\":" + tid + ",\"product\":\"" + filter + "\"}"
                        + "</szJsonPara>"
                        + "</GetTaskBreed>"
                        + "</soap:Body>"
                        + "</soap:Envelope>";
                Log.d("debug", String.valueOf(url));
                Log.d("debug_param", String.valueOf(param));
                AsyncClienter.Ws(YangPinAddActivity.this, url, param, new TextHttpResponseHandler() {
                            @Override
                            public void onFailure(int arg0, Header[] arg1, String arg2,
                                                  Throwable arg3) {
                                // TODO Auto-generated method stub
                                Log.d("数据ERR", arg2);
                            }

                            @Override
                            public void onSuccess(int arg0, Header[] arg1, String arg2) {
                                // TODO Auto-generated method stub
                                Log.d("debugdata", arg2);
                                String[] da = arg2.split("<GetTaskBreedResult>");
                                if (da.length > 1) {
                                    try {
                                        JSONObject das = new JSONObject(da[1].split("</GetTaskBreedResult>")[0]);
                                        JSONArray objents = das.optJSONArray("data");


                                        ArrayList<TextInfo> wvBeiJianDanWeiDatas = new ArrayList<TextInfo>();


                                        for (int i = 0; i < objents.length(); i++) {
                                            JSONObject c2 = objents.optJSONObject(i);
                                            TextInfo textInfo = new TextInfo(c2.optString("breed_id"),
                                                    c2.optString("breed_name"), c2);
                                            wvBeiJianDanWeiDatas.add(textInfo);
                                        }
                                        if (objents.length() == 0) {
                                            JSONObject c3 = new JSONObject();
                                            c3.put("breed_id", "0");
                                            c3.put("breed_name", String.valueOf(etBeiJianDanWeiFilter.getText()));
                                            TextInfo textInfo = new TextInfo("0", String.valueOf(etBeiJianDanWeiFilter.getText()), c3);
                                            wvBeiJianDanWeiDatas.add(textInfo);

                                        }

                                        adpBeiJianDanWeiAdapter.setData(wvBeiJianDanWeiDatas);


                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                }
                            }
                        },
                        "http://tempuri.org/GetTaskBreed");


            }
        }
        final onPage pager = new onPage();
        bottomBeiJianDanWeiWindowLayout.findViewById(R.id.pageLeft).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                page--;
                if (page < 0) {
                    page = 0;
                }
                pager.onClick(0);
            }
        });
        bottomBeiJianDanWeiWindowLayout.findViewById(R.id.pageRight).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                page++;
                pager.onClick(0);
            }
        });
        //zl

        ViewGroup btnBottomBack = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                .findViewById(R.id.btnBack);

        btnBottomBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                bottomWindow.dismiss();
            }
        });

        ViewGroup beiJianDanWeiBommtomSure = (ViewGroup) bottomBeiJianDanWeiWindowLayout
                .findViewById(R.id.btnSure);

        beiJianDanWeiBommtomSure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (wvBeiJianDanWei.getTag() == null)
                    return;
                int sel = java.lang.Integer.parseInt(String.valueOf(wvBeiJianDanWei.getTag()));
                TextInfo textInfo = (TextInfo) adpBeiJianDanWeiAdapter.getItem(sel);
                if (textInfo != null && textInfo.data != null) {
                    yangPin.setName(textInfo.mText);
                    yangPin.setBreedId(String.valueOf(textInfo.id));
                    sureName();
                }
                bottomWindow.dismiss();
            }
        });
        // 检查单位根据名字进行过滤
        bottomBeiJianDanWeiWindowLayout.findViewById(R.id.btn_search).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                page = 0;
                pager.onClick(0);
            }
        });

        pager.onClick(0);

    }

    EditText etBeiJianDanWeiFilter;
    ListAdapter adpBeiJianDanWeiAdapter;
    /**
     * 定位
     */
    ProgressDialog m_pDialog = null;

    protected void show() {
        hide();
        m_pDialog = new ProgressDialog(this);
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        m_pDialog.setTitle("提示");

        m_pDialog.setMessage("正在加载请稍后...");

        m_pDialog.setCancelable(true);

        m_pDialog.show();
    }

    protected void hide() {
        if (m_pDialog != null) {
            try {
                m_pDialog.hide();
            } catch (java.lang.Exception e) {

            } finally {

                m_pDialog = null;
            }
        }
    }
    /**定位相关*/
    /**
     * 定位SDK的核心类
     */
    private LocationClient mLocClient = null;

    private void dwdo() {
        if (mLocClient == null) {
            mLocClient = new LocationClient(getApplicationContext());
            mLocClient.registerLocationListener(new BDLocationListenerImpl());//注册定位监听接口

            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true); //打开GPRS
            option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
            option.setPriority(LocationClientOption.NetWorkFirst); // 设置GPS优先
            option.setScanSpan(20000);
            option.disableCache(true);//禁止启用缓存定位
            option.setLocationNotify(false);
            option.setAddrType("all");
            mLocClient.setLocOption(option);  //设置定位参数

        }
        show();
        mLocClient.start();
    }

    TextView addrinput;

    public class BDLocationListenerImpl implements BDLocationListener {

        /**
         * 接收异步返回的定位结果，参数是BDLocation类型参数
         */
        @Override
        public void onReceiveLocation(BDLocation location) {
            hide();
            if (location == null) {
                Toast.makeText(YangPinAddActivity.this, "获取地点失败,请稍后重试...",
                        Toast.LENGTH_SHORT).show();
                return;
            } else {
                mLocClient.stop();
                if (location.getAddrStr() == null) {
                    Toast.makeText(YangPinAddActivity.this, "获取地点失败,请稍后重试...",
                            Toast.LENGTH_SHORT).show();
                    return;

                }
                Log.d("debug", String.valueOf(location.getCity()));
                addrinput.setText(location.getAddrStr());
            }

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    public void checkBianhao(String no) {
        Toast.makeText(YangPinAddActivity.this,
                "正在联网查询样品编号是否存在..", Toast.LENGTH_SHORT).show();
        String url = Conf.v1609_presample + "CheckSampleNoExist";
        String param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body>"
                + "<CheckSampleNoExist xmlns=\"http://tempuri.org/\">"
                + "<nAddFrom>1</nAddFrom>"
                + "<szAddFirm>android</szAddFirm>"
                + "<nOffset>0</nOffset>"
                + "<nSize>10</nSize>"
                + "<szJsonPara>{\"user\":\"" + user.getUsername() + "\", \"sample_no\":\"" + no + "\"}"
                + "</szJsonPara>"
                + "</CheckSampleNoExist>"
                + "</soap:Body>"
                + "</soap:Envelope>";
        Log.d("debug_param", String.valueOf(param));
        AsyncClienter.Ws(YangPinAddActivity.this, url, param, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int arg0, Header[] arg1, String arg2,
                                          Throwable arg3) {
                        // TODO Auto-generated method stub
                        Log.d("数据ERR", arg2);
                    }

                    @Override
                    public void onSuccess(int arg0, Header[] arg1, String arg2) {
                        // TODO Auto-generated method stub
                        Log.d("debugdata", arg2);
                        String[] da = arg2.split("<CheckSampleNoExistResult>");
                        if (da.length > 1) {
                            try {
                                JSONObject das = new JSONObject(da[1].split("</GetTaskBreedResult>")[0]);
                                JSONObject objents = das.optJSONObject("data");
                                if (objents.optString("exist").equals("false")) {
                                    Intent data_intent = new Intent();

                                    if (chanpinleibie != null) {
                                        yangPin.setKind(chanpinleibie.getId());
                                    }
                                    data_intent.putExtra("yangpin", yangPin);

                                    data_intent.putExtra("edit", edit);

                                    setResult(
                                            YangPinXinXiActivity.TO_ADD_YANGPINXINXI,
                                            data_intent);

                                    finish();


                                    return;

                                }
                            } catch (java.lang.Exception e) {

                            }
                            DialogUtil.showMessageDialog("样品已经存在..",
                                    null, YangPinAddActivity.this);
                        }


                    }
                },

                "http://tempuri.org/CheckSampleNoExist");


    }
}
 
